import {Component, OnInit, OnDestroy, ViewEncapsulation} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {Subject} from "rxjs/Subject";
import {Subscription} from "rxjs/Subscription";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {ToolbarService} from "@shared/components/toolbar/toolbar.service";
import {CrowdService} from "@crowd/crowd.service";
import {ToolsService} from "@shared/service/tools/tools.service";
import {ValidationService} from "@shared/service/validator/validator.service";

@Component({
  selector: 'seed-step-3',
  templateUrl: './step-3.component.html',
  styleUrls: ['./step-3.component.scss', '../common.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class Step3Component implements OnInit, OnDestroy {

  public ngUnsubscribe: Subject<void> = new Subject<void>();
  public subscription: Subscription = new Subscription();
  public step3Form: FormGroup;
  public tipsShow = false;
  public totalMoney = 0.00;
  public nowCheck = false;
  public startTime: any;
  public params = {
    "crowdCode": "",
    "crowdEndTime": "",
    "crowdMoney": 0
  };
  public skuList: any;

  constructor(
    public router: Router,
    private formbuilder: FormBuilder,
    public crowdService: CrowdService,
    private route: ActivatedRoute,
    public toolBarService: ToolbarService,
    public toolsServices: ToolsService
  ) {
    /**
     * @description 获取草稿信息，若草稿内有内容，则赋值给保存参数对象params，并显示出来；
     * @author baoww765
     * @date 2017-11-13
     * */
    this.route.queryParams.takeUntil(this.ngUnsubscribe).subscribe(param => {
      this.params.crowdCode = param['crowdCode'];
      this.startTime = param['activeStartTime'];
      this.crowdService.getCrowdInfo(param['crowdCode'])
        .takeUntil(this.ngUnsubscribe).subscribe(res => {
        if (res.result === '0') {
          const threeData = res;
          this.skuList = threeData.data.twoReq.rightList;
          const that = this;
          if (this.skuList) {
            this.skuList.forEach(function (e) {
              that.totalMoney = that.totalMoney + (e.price / 100) * e.quantity;
            });
          }
          const nowTime = new Date().getTime();
          const crowdEndTime = threeData.data.threeReq['crowdEndTime'];
          const crowd = this.step3Form.controls;
          if (crowdEndTime && parseInt(crowdEndTime, 10) > nowTime) {
            this.nowCheck = true;
          } else {
            this.nowCheck = false;
          }
          this.step3Form.controls['crowdMoney'].setValue(
            threeData.data.threeReq['crowdMoney'] ? threeData.data.threeReq['crowdMoney'] / 100 : '');
          if (crowdEndTime) {
            crowd['crowdEndTime'].setValue(crowdEndTime);
          }
          this.params.crowdEndTime = crowdEndTime ? crowdEndTime : '';
          crowd['crowdMoney'].setValidators(
            [Validators.required, Validators.minLength(1), Validators.maxLength(6), Validators.max(that.totalMoney), Validators.min(1)]);
          crowd['crowdEndTime'].setValidators(
            [Validators.required, ValidationService.endTime(that.startTime)]);
        }
      });
    });
    this.step3Form = this.formbuilder.group({
      crowdMoney: ['', []],
      crowdEndTime: ['', []],
    });
  }

  ngOnInit() {

  }

  /**
   * @description 设置显示隐藏提示信息
   * @author baoww765
   * @date 2017-11-11
   * */
  showTips() {
    this.tipsShow = !this.tipsShow;
  }

  /**
   * @description 选择众筹结束时间，其中需要判断所处理时间是时间戳还是年/月/日 时：分格式，判断该日期与当前日期先后关系
   * @author baoww765
   * @date 2017-11-11
   * */
  dealEndTime() {
    const nowTime = new Date().getTime();
    if (this.step3Form.controls['crowdEndTime'].value) {
      let crowdEndTime;
      if (typeof(this.step3Form.controls['crowdEndTime'].value) === 'string') {
        crowdEndTime = this.crowdService.dealTimeStamp(this.step3Form.controls['crowdEndTime'].value);
      } else {
        crowdEndTime = this.step3Form.controls['crowdEndTime'].value;
      }
      this.params.crowdEndTime = crowdEndTime;
      if (parseInt(this.params.crowdEndTime, 10) > nowTime) {
        this.nowCheck = true;
      } else {
        this.nowCheck = false;
      }
    }
  }

  /**
   * @description 发布众筹，发布之前处理价格单位转换，
   * 此处发布之后向后面传递的crowdCode只采用保存第三步之后后台重新返回的crowdCode(即新的众筹编码)
   * @author baoww765
   * @date 2017-11-13
   * */
  submitLaunch() {
    this.params.crowdMoney = this.step3Form.value.crowdMoney * 100;
    this.crowdService.saveThree(this.params)
      .takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0') {
        this.router.navigate([`/crowd/launch-result`], {queryParams: {crowdCode: res.data.crowdCode}});
      } else {
        this.toolsServices.showToast(res.msg);
      }
    });
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }
}
